package com.web.crawler;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static spark.Spark.*;

public class SearchWebService {
    public static void main(String[] args) {
        port(8080);

        staticFiles.location("/public");

        get("/search", (req, res) -> {
            String query = req.queryParams("q");
            String lang = req.queryParams("lang");

            if (query == null || query.isEmpty()) {
                return "请输入关键词";
            }

            if (lang == null || (!lang.equals("en") && !lang.equals("zh"))) {
                lang = "en"; // 默认英文
            }

            try {
                List<Map<String, Object>> results = SearchService.search(query, lang);

                StringBuilder html = new StringBuilder();
                html.append("<html><body>");
                html.append("<h1>查询结果为: ").append(query).append("</h1>");

                if (results.isEmpty()) {
                    html.append("<p>没有查询到结果.</p>");
                } else {
                    html.append("<ul>");
                    for (Map<String, Object> result : results) {
                        html.append("<li>");
                        html.append("<h2>").append(result.get("title")).append("</h2>");
                        String content = (String) result.get("content");
                        html.append("<p>").append(content.substring(0, Math.min(200, content.length()))).append("...</p>");
                        //html.append("<p>").append(content).append("...</p>");
                        html.append("</li>");
                    }
                    html.append("</ul>");
                }

                html.append("</body></html>");
                return html.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return "查询失败";
            }
        });
    }
}